<?php
require_once 'phpFlickr.php';
require_once 'apikey.php';
require_once 'helpers.php';

class DuplicatesSearch
{
    public $status;
    private $status_count = 1;
    private $year;
    private $dupatt;
    private $phpFlickr;
    private $page_count;
    private $last_page = 0;
    private $all_pages = array();
    private $photoslistcomplete = false;
    private $duplicatelistcomplete = false;
    public $done = false;
    public $results;
    
    public function getStatus()
    {
        return $this->status;
    }
    
    public function setStatus( $update )
    {
       $this->status = $this->status . $this->status_count++ . " " . $update . "\n";
    }
    
// doNext() will implement the next step in getting the entire list of duplicates.    
    public function doNext()
    {
        $result = '';
        if (!$this->photoslistcomplete){
            $result = $this->getPhotoList($this->last_page + 1);       
        }
		elseif (!$this->duplicatelistcomplete) {
            $result = $this->makeDuplicateList();
        } 
        if(!$this->done){
            $this->setStatus($result);
        }
        else {
            return;
        }
    }
    
    public function __construct($form)
    {
        $this->phpFlickr = new phpFlickr(API_KEY, API_SECRET);
        //$this->phpFlickr->enableCache("db", "mysql://stconrad:TitgP47@mysql.seantconrad.com/flickrocd");
        
        $this->year = $form->getValue('year');
        $this->flickrid = $form->getValue('flickrid');
        $this->privacy = $form->getValue('privacy');
        $this->dupatt = $form->getValue('dupatt'); 

        if ($this->privacy == 'private'){
            $this->phpFlickr->auth("delete", true);
            $this->flickrid = "me";
        }
        else {
            //TO DO: We need to handle a failure here.
            $person = $this->phpFlickr->people_findByUsername($this->flickrid);
            $this->flickrid = $person['nsid'];
        }
    }
// getPhotoList() will use the Flickr Search API to get the photos and 
// necessary metadate for the page number passed in. By default, it gets page 1.
// When finished, the flag $photoslistcomplete is set to true, and $all_photos
// contains a list of all the phot    
    private function getPhotoList($page)
    {
        if('' !=  $this->year) {
            $photos = $this->phpFlickr->photos_search(array(
                "user_id"=>$this->flickrid,
                "sort"=>"date-taken-asc",
                "min_taken_date"=>$this->year . "-01-01 00:00:01",
                "max_taken_date"=>($this->year + 1). "-01-01 00:00:01",
                "page"=>$page,
                "per_page"=>"50"));
        }
        else {
            $photos = $this->phpFlickr->photos_search(array(
                "user_id"=>$this->flickrid,
                "sort"=>"date-taken-asc",
                "page"=>$page,
                "per_page"=>"50"));
        }
        
        if(!is_array($photos)){
            throw new Exception("phpFlickr Error: " . $this->phpFlickr->error_code . " " . $this->phpFlickr->error_msg . " " . implode ("+", array(
            "user_id"=>$this->flickrid,
            "sort"=>"date-taken-asc",
            "min_taken_date"=>$this->year . "-01-01 00:00:01",
            "max_taken_date"=>($this->year + 1). "-01-01 00:00:01",
            "page"=>$page,
            "per_page"=>"500")));
        }

        $this->page_count = $photos['pages'];
        $this->last_page = $page;
        
        if (0 == $this->page_count) {
			$this->photoslistcomplete = true;
			return "No photos found for those parameters.";
		}
        
        switch ($this->dupatt){
            case "exiftaken":
                $DateTimeOriginal = '';
                foreach ($photos['photo'] as $photo) {
                            
                    $EXIF = $this->phpFlickr->photos_getExif($photo['id']);

                    foreach($EXIF['exif'] as $key => $value)
                    {
                        if(is_array($value))
                        {
                            //if($value['tag'] == "ImageDataSize") {
                            //    $bytesize = $value['raw'];
                            //    break;
                            //}
                            
                            if($value['tag'] == "DateTimeOriginal") {
                                $DateTimeOriginal = $value['raw'];
                                break;
                            }
                        }
                    }
                    if('' != $DateTimeOriginal){//'' != $bytesize) {            
                        $this->all_photos[$photo['id']] = array("photo"=>$photo, "dupatt"=>$DateTimeOriginal);
                        $DateTimeOriginal = ''; 
                    }
                }
                break;
            case "name":
            default:
                $title = '';
                foreach ($photos['photo'] as $photo) {
                    $this->all_photos[$photo['id']] = array("photo"=>$photo, "dupatt"=>$photo['title']);
                }
                break;
        }

        if($this->page_count == $this->last_page){
            $this->photoslistcomplete = true;
        }
        return "Fetched page " . $this->last_page . " of " . $this->page_count . " of the photo list.";
    }

 // makeDuplicateList() cycles throught the photos and generates
 // a result list of sets of duplicates, based on the selected
 // duplicate attirbute.
    private function makeDuplicateList()
    {
        //Copy photos to array using dupatt as key, collisions mean we have a duplicate
        $temp_array = array();
        $flag_array = array();
        
        
        foreach($this->all_photos as $key=>$photoinfo)
        {
            $value = $photoinfo['dupatt'];

            if(!isset($temp_array[$value])) {
                //Not a duplicate yet, store just the one photo
                $temp_array[$value] = $photoinfo;
            } 
            else { //We have a duplicate
                //Keep a count of dups in flag_array
                if(isset($flag_array[$value])){
                    $flag_array[$value]++;
                }
                else {
                    $flag_array[$value] = 2;
                }
                
            
                //Get necessary data for view for both photos
                $photo = $photoinfo['photo'];
                $id = $photo['id'];
                $url = "http://www.flickr.com/photos/" . $photo['owner'] . "/" . $photo['id'];
                $thumb_url = $this->phpFlickr->buildPhotoURL($photo, "thumbnail");//Can we not hit Flickr?
                $title = $photo['title'];
                if(isset($photo['description'])){
                    $description = $photo['description'];
                }
                else {
                    $description =  '';
                }
  
                $photoarray = array(
                    "id"=>$key, 
                    "url"=>$url,
                    "title"=>$title,
                    "description"=>$description,
                    "thumbnail"=>$thumb_url);

                if ($flag_array[$value] > 2) {
                    //We already have two, just push on the end
                    array_push($temp_array[$value], $photoarray);
                }
                else {
                    //Make an array for both, start with first
                    $photo1 = $temp_array[$value]['photo']; 
                    $id1 = $photo1['id'];
                    $url1 = "http://www.flickr.com/photos/" . $photo1['owner'] . "/" . $photo1['id'];
                    $thumb_url1 = $this->phpFlickr->buildPhotoURL($photo1, "thumbnail");
                    $title1 = $photo1['title'];
                    if(isset($photo1['description'])){
                        $description1 = $photo1['description'];
                    }
                    else {
                        $description1 =  '';
                    }
                    
                    $firstphotoarray = array(
                        "id"=>$id1, 
                        "url"=>$url1,
                        "title"=>$title1,
                        "description"=>$description1,
                        "thumbnail"=>$thumb_url1);
                    
                    $temp_array[$value] = array($firstphotoarray, $photoarray);
                }
            }
        }

        //Copy just the duplicates to new array
        $results = array();  
        foreach($temp_array as $key => $value)
        {
            if (isset($flag_array[$key])) {
                $results[$key] = $value;            
            }
        }
        $this->duplicatelistcomplete = true;
        $this->done = true;
        $this->results = $results;
        return "Done.";
    }

// deleteDuplicates($duplist) takes a list of photos from
// the form, confirms they were on the original list, and
// then deletes them. $duplist should be an array of photo
// id to delete.
// TODO: This may time out. We might have to make it go in steps.
    public function deleteDuplicates($duplist)
    {
        // Confirm we have permissions with Flickr
        $this->phpFlickr->auth("delete", true);
        
        $count = 0;
        //Make sure $duplist is in our photo set
        foreach ($duplist as $id) {
            $this->phpFlickr->photos_delete($id);
            $count++;
            if ($this->phpFlickr->getErrorMsg()) {
                throw new Exception("phpFlickr Error: ID:" . $id . " " . $this->phpFlickr->error_code . " " . $this->phpFlickr->error_msg);
            }
        }
        
        return ($count . " photo(s) successfully deleted!");
    }

// Takes a list of photo id and returns an array of thumbnail URL
// and photo URL
    public function getThumbURLList($id_list) {

        $returnArr = array();
        foreach ($id_list as $id) {
            $photoinfo = $this->all_photos[$id];
            //TODO: Throw error here if not found
            
            $photo = $photoinfo['photo'];
            $id = $photo['id'];
            $url = "http://www.flickr.com/photos/" . $photo['owner'] . "/" . $photo['id'];
            $thumb_url = $this->phpFlickr->buildPhotoURL($photo, "thumbnail");//Can we not hit Flickr?
            $returnArr[$id] = array("url"=>$url, "thumbnail"=>$thumb_url);            
        }
        return $returnArr;
    }
}
?>